import axios from 'axios'

import { Loading,Message } from 'element-ui'
// import Vuex from 'vuex'
// import Router from '@/router/index'
axios.defaults.withCredentials = false // 若跨域请求需要带 cookie 身份识别
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

const loading = {
  loadingInstance:null, //loading 实例
  open: function () {
    if(this.loadingInstance === null){
      this.loadingInstance = Loading.service({
        target: '.main',
        text:'拼命加载中',
        background:'rgba(0,0,0,.5)'
      })
    }
  },
  close:function () {
    if(this.loadingInstance !== null){
      this.loadingInstance.close()
    }
    this.loadingInstance = null
  }
}
const request = axios.create({
  baseURL:"https://TOWIN.method-ad.cn/api/",
  timeout:5000,
  headers:{
    'X-Requested-With': 'XMLHttpRequest',
  }
})
//请求拦截
request.interceptors.request.use(config => {
  // loading.open()
    var token = localStorage.getItem('token')
    // console.log(token)
    // config.data['token'] = token
    var data = config.data
    if(!data){
        config.data = {token};
    }else{
        config.data['token'] = token
    }
    // data['token'] = token
    // console.log(data)
    // config.headers.common['token'] = token
    return config
},error => {
    loading.close()
  //出现异常
})
//相应拦截
request.interceptors.response.use(response => {
  // loading.close()
  //响应拦截，判断返回errcode是不是正确，如果不正确的话进行的处理
//   const resp = response.data
    if(Object.prototype.toString.call(response.data ) === '[object Object]'){
        return response.data
    }else{
        return JSON.parse(response.data)
    }

},error => {
  loading.close()
  Message({
    message:error.message || '系统异常',
    type:'warning',
    duration:5*1000,
    // onClose:()=>{
    // //   Router.push({path: '/login'})
    // }
  })
  //出现异常
})

export default request